// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 加载科室选项
    loadDepartments();
    // 加载初始床位信息
    loadBedInfo();
    
    // 初始化关闭按钮事件监听
    initializeModalEvents();
});

// 初始化模态框事件
function initializeModalEvents() {
    // 关闭按钮点击事件
    document.addEventListener('click', function(event) {
        if (event.target.matches('.close')) {
            closeModal();
        }
    });

    // 点击模态框外部关闭
    const modal = document.getElementById('bed-detail-modal');
    if (modal) {
        modal.addEventListener('click', function(event) {
            if (event.target === modal) {
                closeModal();
            }
        });
    }

    // 添加 ESC 键关闭模态框
    document.addEventListener('keydown', function(event) {
        if (event.key === 'Escape') {
            closeModal();
        }
    });
}

// 加载科室选项
function loadDepartments() {
    fetch('/api/departments')
        .then(response => response.json())
        .then(data => {
            if (data.msg === 'success') {
                const select = document.getElementById('department-select');
                data.departments.forEach(dept => {
                    const option = document.createElement('option');
                    option.value = dept.dept_name;
                    option.textContent = dept.dept_name;
                    select.appendChild(option);
                });
            }
        })
        .catch(error => console.error('Error:', error));
}

// 根据选择的科室更新病区选项
function updateWardOptions() {
    const deptName = document.getElementById('department-select').value;
    const wardSelect = document.getElementById('ward-select');
    wardSelect.innerHTML = '<option value="">全部病区</option>';

    if (deptName) {
        fetch(`/api/departments/${encodeURIComponent(deptName)}/wards`)
            .then(response => response.json())
            .then(data => {
                if (data.msg === 'success') {
                    data.wards.forEach(ward => {
                        const option = document.createElement('option');
                        option.value = ward.ward_id;
                        option.textContent = ward.ward_id;
                        wardSelect.appendChild(option);
                    });
                }
            })
            .catch(error => console.error('Error:', error));
    }
    
    // 更新床位信息
    loadBedInfo();
}

// 加载床位信息
function loadBedInfo() {
    const deptName = document.getElementById('department-select').value;
    const wardId = document.getElementById('ward-select').value;
    
    let url = '/api/beds';
    if (deptName) url += `?dept=${encodeURIComponent(deptName)}`;
    if (wardId) url += `${deptName ? '&' : '?'}ward=${encodeURIComponent(wardId)}`;

    fetch(url)
        .then(response => response.json())
        .then(data => {
            if (data.msg === 'success') {
                updateStats(data.stats);
                displayBeds(data.beds);
            }
        })
        .catch(error => console.error('Error:', error));
}

// 更新统计信息
function updateStats(stats) {
    document.getElementById('total-beds').textContent = stats.total;
    document.getElementById('used-beds').textContent = stats.used;
    document.getElementById('usage-rate').textContent = `${stats.rate}%`;
}

// 显示床位信息
function displayBeds(beds) {
    const container = document.getElementById('beds-grid');
    container.innerHTML = '';

    beds.forEach(bed => {
        const bedCard = document.createElement('div');
        bedCard.className = `bed-card ${bed.used_status ? 'occupied' : 'available'} dept-${bed.dept_name}`;
        bedCard.onclick = () => showBedDetail(bed.bed_id);

        bedCard.innerHTML = `
            <div class="bed-header">
                <h3>${bed.bed_id}</h3>
                <div class="bed-status ${bed.used_status ? 'status-occupied' : 'status-available'}">
                    ${bed.used_status ? '已占用' : '空闲'}
                </div>
            </div>
            <div class="bed-info">
                ${bed.used_status ? `
                    <p><i class="fas fa-user"></i> 患者：${bed.patient_name || '未知'}</p>
                ` : ''}
                <p><i class="fas fa-hospital"></i> 病区：${bed.ward_id}</p>
                <p><i class="fas fa-clinic-medical"></i> 科室：${bed.dept_name}</p>
            </div>
        `;

        container.appendChild(bedCard);
    });

    // 如果床位数不是3的倍数，添加空白卡片保持布局
    const remainder = beds.length % 3;
    if (remainder !== 0) {
        for (let i = 0; i < (3 - remainder); i++) {
            const emptyCard = document.createElement('div');
            emptyCard.className = 'bed-card empty';
            emptyCard.style.visibility = 'hidden';
            container.appendChild(emptyCard);
        }
    }
}

// 显示床位详情
function showBedDetail(bedId) {
    fetch(`/api/beds/${bedId}`)
        .then(response => response.json())
        .then(data => {
            console.log(data);
            if (data.msg === 'success') {
                const bedInfo = data.bed_info;
                
                // 创建模态框内容
                const modalContent = `
                    <div class="bed-detail-modal">
                        <div class="bed-detail-header ${bedInfo.used_status ? 'occupied' : 'available'}">
                            <div class="bed-id">${bedInfo.bed_id}</div>
                            <div class="bed-status">
                                <i class="fas ${bedInfo.used_status ? 'fa-bed' : 'fa-check-circle'}"></i>
                                ${bedInfo.used_status ? '已占用' : '空闲'}
                            </div>
                            <button class="close-btn" onclick="closeModal()">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                        
                        <div class="bed-detail-content">
                            <div class="info-section">
                                <div class="section-title">
                                    <i class="fas fa-hospital-alt"></i>
                                    病区信息
                                </div>
                                <div class="info-grid">
                                    <div class="info-item">
                                        <label>所属病区</label>
                                        <span>${bedInfo.ward_id}</span>
                                    </div>
                                    <div class="info-item">
                                        <label>科室</label>
                                        <span>${bedInfo.ward_name}</span>
                                    </div>
                                    <div class="info-item">
                                        <label>位置</label>
                                        <span>${bedInfo.location || '未指定'}</span>
                                    </div>
                                </div>
                            </div>

                            <div class="info-section">
                                <div class="section-title">
                                    <i class="fas fa-user-md"></i>
                                    管理医生
                                </div>
                                <div class="info-grid">
                                    <div class="info-item">
                                        <label>姓名</label>
                                        <span>${bedInfo.doctor_name || '未分配'}</span>
                                    </div>
                                    <div class="info-item">
                                        <label>工号</label>
                                        <span>${bedInfo.doctor_id || '未分配'}</span>
                                    </div>
                                </div>
                            </div>

                            ${bedInfo.patient_info ? `
                                <div class="info-section">
                                    <div class="section-title">
                                        <i class="fas fa-user"></i>
                                        患者信息
                                    </div>
                                    <div class="info-grid">
                                        <div class="info-item">
                                            <label>姓名</label>
                                            <span>${bedInfo.patient_info.patient_name}</span>
                                        </div>
                                        <div class="info-item">
                                            <label>ID</label>
                                            <span>${bedInfo.patient_info.patient_id}</span>
                                        </div>
                                        <div class="info-item">
                                            <label>性别</label>
                                            <span>${bedInfo.patient_info.gender}</span>
                                        </div>
                                        <div class="info-item">
                                            <label>年龄</label>
                                            <span>${bedInfo.patient_info.age}</span>
                                        </div>
                                        <div class="info-item">
                                            <label>入院时间</label>
                                            <span>${bedInfo.patient_info.in_date}</span>
                                        </div>
                                        <div class="info-item">
                                            <label>预计住院</label>
                                            <span>${bedInfo.patient_info.predict_days} 天</span>
                                        </div>
                                        <div class="info-item full-width">
                                            <label>病情描述</label>
                                            <span>${bedInfo.patient_info.description}</span>
                                        </div>
                                    </div>
                                </div>
                            ` : ''}
                        </div>
                    </div>
                `;

                // 创建模态框容器
                const modalContainer = document.createElement('div');
                modalContainer.className = 'modal-overlay';
                modalContainer.innerHTML = modalContent;
                document.body.appendChild(modalContainer);

                // 添加动画效果
                requestAnimationFrame(() => {
                    modalContainer.classList.add('show');
                });
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('获取床位信息失败');
        });
}

// 关闭模态框
function closeModal() {
    const modalContainer = document.querySelector('.modal-overlay');
    if (modalContainer) {
        modalContainer.classList.remove('show');
        setTimeout(() => {
            modalContainer.remove();
        }, 300);
    }
}

// 点击模态框外部关闭
document.addEventListener('click', function(event) {
    if (event.target.classList.contains('modal-overlay')) {
        closeModal();
    }
});

// ESC键关闭模态框
document.addEventListener('keydown', function(event) {
    if (event.key === 'Escape') {
        closeModal();
    }
});

